<?php

function smarty_function_get_provinces($params, &$smarty) {
  
  $endpoint = "http://www.votethailand.com/votedatacenter/index.php?module=VoteDataCenter&type=ws&func=getProvinceList&asc=name";
  $xml = simplexml_load_string(@file_get_contents($endpoint));

  $provinces = xmlToarray($xml);
  $provinceArray = array();
  //var_dump($provinces); 
  $i = 0;
  foreach($provinces as $items){
    foreach($items as $item){
      $provinceArray[$i]['id'] = $item['id'];
      $provinceArray[$i]['name'] = $item['name'];
      $i++;
    }

  }

  $smarty->assign('provinceArray', $provinceArray); 

}


function xmlToArray($obj, $level=0) {
  
  $items = array();
  
  if(!is_object($obj)) return $items;
	  
  $child = (array)$obj;
  
  if(sizeof($child)>1) {
	  foreach($child as $aa=>$bb) {
		  if(is_array($bb)) {
			  foreach($bb as $ee=>$ff) {
				  if(!is_object($ff)) {
					  $items[$aa][$ee] = $ff;
				  } else
				  if(get_class($ff)=='SimpleXMLElement') {
					  $items[$aa][$ee] = xmlToArray($ff,$level+1);
				  }
			  }
		  } else
		  if(!is_object($bb)) {
			  $items[$aa] = $bb;
		  } else
		  if(get_class($bb)=='SimpleXMLElement') {
			  $items[$aa] = xmlToArray($bb,$level+1);
		  }
	  }
  } else
  if(sizeof($child)>0) {
	  foreach($child as $aa=>$bb) {
		  if(!is_array($bb)&&!is_object($bb)) {
			  $items[$aa] = $bb;
		  } else
		  if(is_object($bb)) {
			  $items[$aa] = xmlToArray($bb,$level+1);
		  } else {
			  foreach($bb as $cc=>$dd) {
				  if(!is_object($dd)) {
					  $items[$obj->getName()][$cc] = $dd;
				  } else
				  if(get_class($dd)=='SimpleXMLElement') {
					  $items[$obj->getName()][$cc] = xmlToArray($dd,$level+1);
				  }
			  }
		  }
	  }
  }
  return $items;
}



/*
function xml2array($originalXML, $attributes=true)
{
        $xmlArray = array();
        $search = $attributes ? '|<((\S+)(.*))\s*>(.*)</\2>|Ums' : '|<((\S+)()).*>(.*)</\2>|Ums';
       
        // normalize data
        $xml = preg_replace('|>\s*<|', ">\n<", $originalXML); // one tag per line
        $xml = preg_replace('|<\?.*\?>|', '', $xml);            // remove XML declarations
        $xml = preg_replace('|<(\S+?)(.*)/>|U', '<$1$2></$1>', $xml); //Expand singletons
       
        if (! preg_match_all($search, $xml, $xmlMatches))
                return trim($originalXML);      // bail out - no XML found
               
        foreach ($xmlMatches[1] as $index => $key)
        {
                if (! isset($xmlArray[$key])) $xmlArray[$key] = array();       
                $xmlArray[$key][] = xml2array($xmlMatches[4][$index], $attributes);
        }
        return $xmlArray;
}
*/